//#define __FORCE_TRACE__
//#define __FORCE_DEBUG__
//#define __FORCE_INFO__
#define THIS_FILE "ia\fn_civilianDanger.sqf"
#include <tmf_constants.h>
#include <tmf_macros.h>

TRACE_1("Start",_this);
TMFPROFILERSTART;

private ["_dir","_cnt","_civ","_cause"];
DEFAULT_PARAM(_civ,0,objNull);
DEFAULT_PARAM(_cause,1,objNull);
if (alive _civ) then {
	if (time - (OGETVAR(_civ,QGVAR(CIV_FIRE_LAST),time)) > 200) then {
		OSETVAR(_civ,QGVAR(CIV_FIRE_CNT),0);
	};
	OSETVAR(_civ,QGVAR(CIV_FIRE_LAST),time);
	OSETVAR(_civ,QGVAR(CIV_FIRE_CNT),((OGETVAR(_civ,QGVAR(CIV_FIRE_CNT),0)) + 1));
	_cnt = OGETVAR(_civ,QGVAR(CIV_FIRE_CNT),0);
	DEBUG_1("Civil FiredNear",_cnt);
	_civ setSpeedMode "FULL";
	_civ setBehaviour "STEALTH";
	if (_cnt < 10) then {
		_civ setUnitPosWeak "MIDDLE";
		if (_cnt > 5) then {
			_civ setUnitPosWeak "DOWN";
		};
	} else {
		if !(fleeing _civ) then {
			if (time - (OGETVAR(_civ,QGVAR(CIV_FIRE_MOVE),0)) > 10) then {
				OSETVAR(_civ,QGVAR(CIV_FIRE_MOVE),time);
				DEBUG_1("Civil forced fleeing",_cnt);
				_dir = random(360);
				if (IS_OBJECT(_cause) && {!(isNull _cause)}) then {
					// Fleeing from a unit
					_dir = [_cause,_civ] call FFUNC(dirTo);
					// To give some randomness for the end position and avoiding all civilians running to the same spot.
					_dir = _dir + (random 40) - 20;
				};
				_civ doMove ([getPos _civ, 200, _dir] call FFUNC(relPos2D));
			};
		};
		if (IS_STRING((OGETVAR(_civ,QGVAR(CIV_UNIT_POS),"")))) then {
			DEBUG_1("Civil position down",fleeing _civ);
			_civ setUnitPos "DOWN";
			_civ setVariable [QGVAR(CIV_UNIT_POS),
				_civ spawn {
					sleep (120 + random(60)); 
					if (alive _this) then {
						_this setUnitPos "AUTO"; 
						_this setUnitPosWeak "MIDDLE";
						OSETVAR(_this,QGVAR(CIV_FIRE_CNT),floor((OGETVAR(_this,QGVAR(CIV_FIRE_CNT),0)) / 3));
						OSETVAR(_this,QGVAR(CIV_UNIT_POS),"");
						DEBUG_1("Civil position restored",_this);
						if (!(alive (leader _this)) || leader _this == _this) then {
							[_this] call FFUNC(civilianWaypointCode);
						};
					};
				}
			];
		};
	};
};
TRACE("End");
TMFPROFILERSTOP;